//
//  QWMineInfoController.m
//  assistant
//
//  Created by kevin on 2023/6/8.
//

#import "QWMineInfoController.h"
#import "QWMineInfoCell.h"
#import "FSMediaPicker.h"//相机相册
#import "QWInputController.h"
#import <AFNetworking/AFHTTPSessionManager.h>
//#import "UploadImageApi.h"

@interface QWMineInfoController ()<UITableViewDelegate,UITableViewDataSource,FSMediaPickerDelegate>
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSArray *showArr;
@end

@implementation QWMineInfoController
- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [self.view endEditing:YES];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"个人信息";
    
    [self loadInfo];
    [self tableView];
}

- (void)loadInfo{
    QWqaUserModel *user = AppProfile.qaUserInfo;
    self.showArr = @[
        @{
            @"name":@"头像",
            @"url":IsStringEmpty(user.photo)?@"":user.photo,
        },
        @{
            @"name":@"姓名",
            @"content":IsStringEmpty(user.name)?@"":user.name,
        },
        @{
            @"name":@"医院名称",
            @"content":IsStringEmpty(user.companyId)?@"":user.companyId,
        },
        @{
            @"name":@"科室",
            @"content":IsStringEmpty(user.officeId)?@"":user.officeId,
        },
        @{
            @"name":@"职称",
            @"content":IsStringEmpty(user.level)?@"":user.level,
        },
        @{
            @"name":@"擅长领域",
            @"content":IsStringEmpty(user.major)?@"":user.major,
        },
        @{
            @"name":@"基本简历",
            @"content":IsStringEmpty(user.resume)?@"":user.resume,
        },
        @{
            @"name":@"手机号",
            @"content":IsStringEmpty(user.phone)?@"":user.phone,
            @"hideRightArrow":@true
        }
    ];
}

- (UITableView *)tableView{
    if(!_tableView){
        _tableView =[[UITableView alloc]initWithFrame:self.view.bounds style:UITableViewStyleGrouped];
        _tableView.estimatedRowHeight = 400;
        _tableView.rowHeight = UITableViewAutomaticDimension;
        _tableView.estimatedSectionFooterHeight=0;
        _tableView.estimatedSectionHeaderHeight=0;
        _tableView.showsVerticalScrollIndicator=NO;
        _tableView.showsHorizontalScrollIndicator=NO;
        
        _tableView.delegate =self;
        _tableView.dataSource =self;
        
        [_tableView registerClass:[QWMineInfoCell class] forCellReuseIdentifier:@"QWMineInfoCell"];
        
        _tableView.backgroundColor=Color_TableView_Gray;
        _tableView.separatorStyle=UITableViewCellSeparatorStyleNone;

        
        [self.view addSubview:_tableView];
        [_tableView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.edges.equalTo(self.view);
        }];
        
    }
    return _tableView;
}

#pragma mark- UITableViewDelegate,UITableViewDataSource
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 0.0000001;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 0.0000001;
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.showArr.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    QWMineInfoCell *cell =[tableView dequeueReusableCellWithIdentifier:@"QWMineInfoCell"];
    NSDictionary *dic = self.showArr[indexPath.row];
    cell.nameLabel.text = dic[@"name"];
    cell.secondText = dic[@"content"];
    cell.headerUrl = dic[@"url"];
    cell.hideRightArrow = dic[@"hideRightArrow"];
    return cell;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    [self.view endEditing:YES];
    NSDictionary *dic = self.showArr[indexPath.row];
    NSString *name = dic[@"name"];
    
    if([name isEqualToString:@"头像"]){
        [self headerImageButtonClick];
    }else if (![name isEqualToString:@"手机号"]){
        QWInputController *vc = [[QWInputController alloc]init];
        NSString * content = dic[@"content"];
        vc.inputStr = content;
        vc.title = [NSString stringWithFormat:@"更改%@",name];
        vc.inputType = [name isEqualToString:@"擅长领域"] || [name isEqualToString:@"基本简历"]?InputType_big:InputType_defalut;
        [self.navigationController pushViewController:vc animated:YES];
        
        vc.inputInfoBlock = ^(NSString * _Nonnull value) {
            NSLog(@"%@：%@",name,value);
            [self update:name changeValue:value];
        };
    }
}

#pragma mark- 修改基本信息
- (void)update:(NSString *)name changeValue:(NSString *)value{
    NSMutableDictionary *dic = [AppProfile.qaUserInfo mj_keyValues];
    if([name isEqualToString:@"姓名"]){
        [dic setValue:value forKey:@"name"];
    }
    
    if([name isEqualToString:@"医院名称"]){
        [dic setValue:value forKey:@"companyId"];
    }
    
    if([name isEqualToString:@"科室"]){
        [dic setValue:value forKey:@"officeId"];
    }
    
    if([name isEqualToString:@"职称"]){
        [dic setValue:value forKey:@"level"];
    }
    
    if([name isEqualToString:@"擅长领域"]){
        [dic setValue:value forKey:@"major"];
    }
    
    if([name isEqualToString:@"基本简历"]){
        [dic setValue:value forKey:@"resume"];
    }
    
    [SWHUDUtil showHudViewInSuperView:self.view withMessage:@"请等待"];
    HXPostRequest * request = [[HXPostRequest alloc] initWithRequestUrl:URL_UPDATE argument:dic];
    [request startWithCompletionBlockWithSuccess:^(__kindof HXRequest *request, NSDictionary *result, BOOL success) {
        [SWHUDUtil hideHudView];
        long code = [result[@"code"] longValue];
        if(code == 1){
            AppProfile.qaUserInfo = [QWqaUserModel mj_objectWithKeyValues:dic];
            [AppProfile saveUserDefault:AppProfile.qaUserInfo];
            [self loadInfo];
            [self.tableView reloadData];
            [[NSNotificationCenter defaultCenter] postNotificationName:QWUserInfo_Change_State object:nil];
            
            if([name isEqualToString:@"姓名"]){
                [self hxUpdateNikeName:value];
            }
        }
    } failure:^(__kindof HXRequest *request, NSString *errorInfo) {
        [SWHUDUtil hideHudView];
    }];
    
}

#pragma mark- 修改头像
-(void)headerImageButtonClick
{
    FSMediaPicker *mediaPicker = [[FSMediaPicker alloc] init];
    mediaPicker.mediaType = FSMediaTypePhoto;
    mediaPicker.editMode = FSEditModeStandard;
    mediaPicker.delegate = self;
    NSIndexPath *indexPath=[NSIndexPath indexPathForRow:0 inSection:0];
    UITableViewCell *cell = [_tableView cellForRowAtIndexPath:indexPath];
    [mediaPicker showFromView:cell];
}
- (void)mediaPicker:(FSMediaPicker *)mediaPicker didFinishWithMediaInfo:(NSDictionary *)mediaInfo
{
    if (mediaInfo.mediaType == FSMediaTypeVideo) {
        //        self.player.contentURL = mediaInfo.mediaURL;
        //        [self.player play];
    } else {
        if (mediaPicker.editMode == FSEditModeNone) {
            [self uploadHeadImg:mediaInfo.originalImage];
        } else {
            [self uploadHeadImg:mediaPicker.editMode == FSEditModeCircular? mediaInfo.circularEditedImage:mediaInfo.editedImage];
        }
    }
}
-(void)uploadHeadImg:(UIImage*)img
{
    NSDictionary *dic = @{@"id":AppProfile.qaUserInfo.id};
    [SWHUDUtil showHudViewInSuperView:self.view withMessage:@"请等待"];
    HXPostRequest * request = [[HXPostRequest alloc] initWithRequestUrl:URL_UPLOAD_IMAGE argument:dic constructingBodyBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        NSData *data = UIImageJPEGRepresentation(img,0.5);
        [formData appendPartWithFileData:data
                                    name:@"file"
                                fileName:@"gauge.png"
                                mimeType:@"image/jpeg"];
    }];
    [request startWithCompletionBlockWithSuccess:^(__kindof HXRequest * _Nonnull request, NSDictionary * _Nonnull result, BOOL success) {
        [SWHUDUtil hideHudView];
        long code = [result[@"code"] longValue];
        if(code == 1){
            NSDictionary *dic = result[@"data"];
            AppProfile.qaUserInfo.photo = dic[@"url"];
            [AppProfile chageUserInfo:AppProfile.qaUserInfo];
            [self loadInfo];
            [self.tableView reloadData];
            [[NSNotificationCenter defaultCenter] postNotificationName:QWUserInfo_Change_State object:nil];
            
            [self hxUpdateAvatar];//环信头像
        }
        NSLog(@"");
    } failure:^(__kindof HXRequest * _Nonnull request, NSString * _Nonnull errorInfo) {
        [SWHUDUtil hideHudView];
    }];
}


#pragma mark - 环信基本信息修改
#pragma mark - 环信-头像
- (void)hxUpdateAvatar{
    NSString *url = [QWM_BASE_API_URL stringByAppendingFormat:@"/bokeupload%@",AppProfile.qaUserInfo.photo];
    [[[EMClient sharedClient] userInfoManager] updateOwnUserInfo:url withType:EMUserInfoTypeAvatarURL completion:^(EMUserInfo*aUserInfo,EMError *aError) {
        if(!aError) {
            [[UserInfoStore sharedInstance] setUserInfo:aUserInfo forId:[EMClient sharedClient].currentUsername];
            [[NSNotificationCenter defaultCenter] postNotificationName:USERINFO_UPDATE  object:nil];
        }
    }];
}

#pragma mark - 环信-名称
- (void)hxUpdateNikeName:(NSString *)aName
{
    //设置推送设置
    __weak typeof(self) weakself = self;
    [[EMClient sharedClient].pushManager updatePushDisplayName:aName completion:^(NSString * _Nonnull aDisplayName, EMError * _Nonnull aError) {
        if (!aError) {
            [weakself.tableView reloadData];
        } else {
            [EMAlertController showErrorAlert:aError.errorDescription];
        }
    }];
    [[[EMClient sharedClient] userInfoManager] updateOwnUserInfo:aName withType:EMUserInfoTypeNickName completion:^(EMUserInfo* aUserInfo,EMError *aError) {
            if(!aError) {
                [[UserInfoStore sharedInstance] setUserInfo:aUserInfo forId:[EMClient sharedClient].currentUsername];
                [[NSNotificationCenter defaultCenter] postNotificationName:USERINFO_UPDATE  object:nil];
            }
    }];
}

@end
